//We Read all Scripts with "DV_RLV_" on start and add the next to the Menu List on Click, also we add an Basic Menu Update and such
list gMenu;
list gBasicMenu =["<<","END",">>"];
string gMenuPrefix="DV_MAIN_";
integer gMenuLink =1337;
key ToucherID;

integer gDemon =1338;
integer channel_dialog;
integer listen_id;
string msg ="Main Menu\nVersion 0.1 Beta";

Debug(string _text)
{
    llSay(DEBUG_CHANNEL, _text);
}

makeMenu()
{
    integer _Scripts = llGetInventoryNumber(INVENTORY_SCRIPT); 
    if (_Scripts == 1)
    {
        llOwnerSay ("No other Scripts inside");
    }
    else if (_Scripts > 1)
    {
        integer i=0;
        gMenu=[];

        while(i<_Scripts)
        {
            string _Name;
            _Name= llGetInventoryName(INVENTORY_SCRIPT, i);
            if(llGetSubString(_Name, 0, llStringLength(gMenuPrefix)-1) ==gMenuPrefix )
            {
                gMenu +=llGetSubString(_Name,llStringLength(gMenuPrefix),llStringLength(_Name));
            }
            i++; 
        }
	    if(llGetListLength(gMenu)<10)
		{
			gMenu= [" ","END", " "]+gMenu;
		}
		else
		{
			gMenu+=gBasicMenu;
		} 
    }
}

displayMenu()
{
    channel_dialog = ( 1 * (integer)("0x"+llGetSubString((string)llGetKey(),-5,-1)) );
	listen_id = llListen( channel_dialog, "", NULL_KEY, "");
    llDialog(ToucherID, msg,gMenu, channel_dialog);
    llSetTimerEvent(45.0);
}



default 
{
    state_entry() 
    {
       makeMenu(); 
    }
    
    changed(integer change)
    {
         if (change & CHANGED_INVENTORY)
         { 
             makeMenu();
         }  
    }
    
    touch_start(integer total_number)
    {
        ToucherID = llDetectedKey(0);
        displayMenu();
    }
    
    listen(integer channel, string name, key id, string message)
    {
    	llListenRemove(listen_id);
    	llSetTimerEvent(0.0);
    	llMessageLinked(LINK_THIS, gMenuLink, gMenuPrefix+message, ToucherID);
    }
    
    link_message(integer sender, integer num, string str, key id)
  	{
  		
  		if(num ==gMenuLink)
  		{
  			if(str==llGetScriptName())
  			{
  				ToucherID=id;
  				displayMenu();
  			}
  		}
  		if(num ==gDemon)
  		{
  			if(str!=llGetScriptName())
  			{
				llListenRemove(listen_id);
  			}
  		}
  	}
    
    timer()
    {
    	llSetTimerEvent(0.0);
    	llListenRemove(listen_id);
    }
    
}
